package com.aivin.lib_englishlearn;



import org.xutils.http.RequestParams;

import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;


public class FanyiV3Demo {

    private static FanyiV3Demo fanyiV3Demo ;
    public static FanyiV3Demo getInstance(){
        if(fanyiV3Demo ==null){
            fanyiV3Demo =new FanyiV3Demo() ;
        }
        return fanyiV3Demo ;
    }




    public RequestParams getParams (String q) {
        final String APP_KEY = "4b70bc45509f1c48";
        final String APP_SECRET = "Bu5nVqCTlZNSecyTtWXakBzjnxnkBBGv";

        String salt = String.valueOf(System.currentTimeMillis());
        String curtime = String.valueOf(System.currentTimeMillis() / 1000);
        String signStr = APP_KEY + truncate(q) + salt + curtime + APP_SECRET;
        String sign = getDigest(signStr);

        String API = "https://openapi.youdao.com/api";
        RequestParams params = new RequestParams(API);
        params.addBodyParameter("q",q); // 待翻译文本 , 必须是UTF-8编码
        params.addParameter("from","en");// 源语言
        params.addParameter("to","zh-CHS"); // 目标语言
        params.addParameter("signType","v3"); // 签名类型
        params.addParameter("curtime",curtime); // 当前UTC时间戳(秒)
        params.addParameter("appKey",APP_KEY); // 应用ID
        params.addParameter("salt",salt); // UUID
        params.addParameter("sign",sign); // 签名

        return params;
    }



    /**
     * 生成加密字段
     */
    private  String getDigest(String string) {
        if (string == null) {
            return null;
        }
        char [] hexDigits = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};
        byte[] btInput = string.getBytes(StandardCharsets.UTF_8);
        try {
            MessageDigest mdInst = MessageDigest.getInstance("SHA-256");
            mdInst.update(btInput);
            byte[] md = mdInst.digest();
            int j = md.length;
            char [] str = new char[j * 2];
            int k = 0;
            for (byte byte0 : md) {
                str[k++] = hexDigits[byte0 >>> 4 & 0xf];
                str[k++] = hexDigits[byte0 & 0xf];
            }
            return new String(str);
        } catch (NoSuchAlgorithmException e) {
            return null;
        }
    }


    private   String truncate(String q) {
        if (q == null) {
            return null;
        }
        int len = q.length();
        return len <= 20 ? q : (q.substring(0, 10) + len + q.substring(len - 10, len));
    }
}